using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;

public static class Settings
{
    public static class ConnectionStrings
    {
        public static string AccountsDatabase =
            ConfigurationManager.ConnectionStrings["AccountsDatabase"].ConnectionString;
    }

    internal static void Update(string key, string value)
    {
        using (SqlConnection connection = new SqlConnection(ConnectionStrings.AccountsDatabase))
        {
            SqlCommand command = new SqlCommand("SettingUpdate", connection);
            command.CommandType = CommandType.StoredProcedure;

            command.Parameters.AddWithValue("key", key);
            command.Parameters.AddWithValue("value", value);

            connection.Open();
            command.ExecuteNonQuery();
            connection.Close();
        }
    }

    internal static string Fetch(string key)
    {
        string value = string.Empty;
        using (SqlConnection connection = new SqlConnection(ConnectionStrings.AccountsDatabase))
        {
            SqlCommand command = new SqlCommand("SettingFetch", connection);
            command.CommandType = CommandType.StoredProcedure;
            command.Parameters.AddWithValue("key", key);

            connection.Open();

            SqlDataReader reader = command.ExecuteReader();
            if (!reader.Read())
            {
                throw new InvalidOperationException(
                    "Setting value does not exist for key '" + key + "'.");
            }

            value = (string)reader["SettingValue"];
            connection.Close();
        }
        return value;
    }

    internal static bool Exists(string key)
    {
        bool exists = false;
        using (SqlConnection connection = new SqlConnection(ConnectionStrings.AccountsDatabase))
        {
            SqlCommand command = new SqlCommand("SettingFetch", connection);
            command.CommandType = CommandType.StoredProcedure;
            command.Parameters.AddWithValue("key", key);

            connection.Open();

            SqlDataReader reader = command.ExecuteReader();
            if (reader.Read())
            {
                exists = true;
            }

            connection.Close();
        }
        return exists;
    }
}
